package com.jky.stmall.manger.controller.api;

import com.github.pagehelper.PageInfo;
import com.jky.stmall.manger.entity.Category;
import com.jky.stmall.manger.entity.Result;
import com.jky.stmall.manger.service.CategoryService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 添加注解
 */
@RestController
//相当于Controller 与 ResponseBody结合体
//1.将当前的类放到Spring的bean容器中
//2.该类的所有处理器方法，返回JSON格式的数据
@RequestMapping("/api/category")
//给当前类的所有处理器方法添加url前缀
public class APICategoryController {
    //自动注入Service层对象
    @Resource
    private CategoryService categoryService;

    /**
     * 添加
     */
    @PostMapping
    public Result add(@RequestBody Category category) {
        //@RequestBody 解析客户端发来的JSON格式
        try {
            int code = categoryService.add(category);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            //添加失败
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除 delete
     */
    @DeleteMapping
    public Result remove(Integer id) {
        try {
            int code = categoryService.remove(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @PutMapping
    public Result edit(@RequestBody Category category) {
        try {
            int code = categoryService.edit(category);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据条件查询
     * get请求不能发送json
     */
    @GetMapping
    public Result get(Integer page, Integer limit, Category category) {
        if (page == null) {
            List<Category> list = categoryService.search(category);
            return Result.success(list);
        } else {
            PageInfo pageInfo = categoryService.searchByPage(page, limit, category);
            return Result.success(pageInfo);
        }
    }
    /**
     * 根据id进行查询
     * 通过路径参数传递ID
     */
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") Integer id) {
        //取出路径的参数 绑定到id上
        Category category = categoryService.getById(id);
        if (category == null) {
            return Result.error("ID不存在");
        } else {
            return Result.success(category);
        }
    }
}
